package com.haha.webSocket;

import jakarta.websocket.ContainerProvider;
import jakarta.websocket.DeploymentException;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;

public class Main {

    private static String serverEndpoint = "wss://api.sgroup.qq.com/websocket";
    private static Session session;
    private static MyWebSocketClientEndpoint clientEndPoint;

    public static void main(String[] args) {
        try {
            clientEndPoint = new MyWebSocketClientEndpoint();
            initConnection();
            Thread.sleep(Long.MAX_VALUE);

        } catch (DeploymentException | IOException | URISyntaxException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重连
     */
    public static void reconnection() {
        try {
            if (session != null) {
                session.close();
            }
            while (true) {
                try {
                    try {
                        TimeUnit.SECONDS.sleep(2);
                    } catch (InterruptedException ex) {
                        System.err.println("Interrupted while sleeping: " + ex.getMessage());
                    }
                    initConnection();
                    break;
                } catch (Exception e) {
                    System.out.println("WebSocket reconnection failed. Retrying in 5 seconds...");
                    try {
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException ex) {
                        System.err.println("Interrupted while sleeping: " + ex.getMessage());
                    }
                }
            }
        } catch (Exception  e) {
            e.printStackTrace();
        } finally {
            System.out.println("WebSocket reconnection success.");
        }
    }

    public static void initConnection() throws URISyntaxException, DeploymentException, IOException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        session = container.connectToServer(clientEndPoint, new URI(serverEndpoint));
    }

}